package com.yutel.system.struts.extjs;

import java.util.HashMap;
import java.util.Set;

import com.yutel.system.repository.ExtComm;
import com.yutel.system.repository.ExtPanel;

public class GridPanel extends BasePanel{
	public String make(ExtPanel panel){
		StringBuffer sb=new StringBuffer();
		if(comm(panel)){
			sb.append(editForm(panel));
			sb.append("P").append(panel.getId()).append("= Ext.extend(Ext.grid.GridPanel, { \n");
			sb.append(" buttonEnable: function(){ \n");
			sb.append("	 this.getTopToolbar().enable(); \n");	
			sb.append(" }, \n");
			sb.append(" buttonDisable: function(){ \n");
			sb.append("  this.getTopToolbar().disable(); \n");	
			sb.append(" }, \n");
			sb.append(" initComponent : function() { \n");
			sb.append("   var templateGridPanel = this; \n");
			if(map.get("butItem")!=null) {
				sb.append(but.toString());
			}
			sb.append("   var cm = new Ext.grid.ColumnModel([new Ext.grid.CheckboxSelectionModel(), \n");
			sb.append(cm.toString()).append("]); \n");
			sb.append("   var ds = new Ext.data.Store({ \n");
			sb.append("     autoLoad : false, \n");
			sb.append("     proxy : new Ext.data.HttpProxy({ \n");
			sb.append("       url : 'tempList.action' \n");
			sb.append("     }), \n");
			sb.append("     reader : new Ext.data.JsonReader({ \n");
			sb.append("       totalProperty : 'totalProperty', \n");
			sb.append("       root : 'root' \n");
			sb.append("     }, [ \n").append(ds.toString()).append("]) \n");
			sb.append("    }); \n");
			sb.append(" Ext.apply(this, { \n");
			sb.append("   id:'wyid").append(panel.getId()).append("',");
			sb.append("   frame:true,border:true,");
			sb.append("   autoScroll : true, \n");
			sb.append("   autoHeight : false, \n");
			sb.append("   title:'").append(panel.getName()).append("',");
			if(panel.getRegion()!=null && !"".equals(panel.getRegion())) {
				sb.append("region : '").append(panel.getRegion()).append("', \n");
			}
			sb.append("    bodyStyle : 'width:100%', \n");
			sb.append("    loadMask : { \n");
			sb.append("       msg : '数据加载中...' \n");
			sb.append("    }, \n");
			sb.append("    viewConfig : { \n");
			sb.append("      forceFit : true \n");
			sb.append("    }, \n");
			if(map.get("butItem")!=null) {
				sb.append("  tbar:[").append(map.get("butItem")).append("], \n");
			}
			sb.append("    cm : cm, \n");
			sb.append("    ds : ds, \n");
			sb.append("    sm : new Ext.grid.CheckboxSelectionModel({ \n");
			sb.append("       singleSelect : false \n");
			sb.append("    }), \n");
			sb.append("    enableColumnMove : false, \n");
			sb.append("    clicksToEdit : 1 \n");
			sb.append("  }); \n");
			sb.append("P").append(panel.getId()).append(".superclass.initComponent.call(this);");
			sb.append(" } \n");
			sb.append("}); \n");
		} else {
			sb.append("P").append(panel.getId()).append("= Ext.extend(Ext.Panel, { \n");
			sb.append("initComponent : function() { \n");
			sb.append(" Ext.apply(this, {");
			sb.append("   id:'wyid").append(panel.getId()).append("',");
			sb.append("   title:'页面错误',");
			sb.append("   frame : true,border:true,");
			sb.append("   html:'请检查面版的列表设置！").append("', \n");
			sb.append(" }); \n");
			sb.append("P").append(panel.getId()).append(".superclass.initComponent.call(this);");
			sb.append("} \n");
			sb.append("}); \n");
		}
		return sb.toString();
	}
	private String editForm(ExtPanel panel){
		StringBuffer sb=new StringBuffer();
		sb.append("EditW").append(panel.getId()).append("= Ext.extend(Ext.Window, { \n");
		sb.append(" tempId :1, \n");
		sb.append(" initData : function(){ \n");
		sb.append("  var myform=this.items.itemAt(0); \n");
		sb.append("  ajaxRequest('tempView.action', { \n");
		sb.append("    'temp.id':this.tempId, \n");
		sb.append("    'temp.panelId':").append(panel.getId()).append(", \n");
		sb.append("    'temp.tableName':'").append(panel.getTableName()).append("' \n");
		sb.append("   }, myform, function(result) { \n");
		sb.append(field);
//		sb.append("    var fieldArr = myform.findByType('textfield'); \n");
//		sb.append("    for (var i = 0; i < fieldArr.length; i++) { \n");
//		sb.append("     var targetName = fieldArr[i].getName(); \n");
//		sb.append("     var targetValue = result[targetName]; \n");
//		sb.append("     alert(targetName+','+targetValue);");
//		sb.append("     fieldArr[i].setValue(targetValue); \n");
//		sb.append("    } \n");
//		sb.append("    fieldArr = myform.findByType('numberfield'); \n");
//		sb.append("    for (var i = 0; i < fieldArr.length; i++) { \n");
//		sb.append("     var targetName = fieldArr[i].getName(); \n");
//		sb.append("     var targetValue = result[targetName]; \n");
//		sb.append("     fieldArr[i].setValue(targetValue); \n");
//		sb.append("    } \n");
//		sb.append("    fieldArr = myform.findByType('textarea'); \n");
//		sb.append("    for (var i = 0; i < fieldArr.length; i++) { \n");
//		sb.append("     var targetName = fieldArr[i].getName(); \n");
//		sb.append("     var targetValue = result[targetName]; \n");
//		sb.append("     fieldArr[i].setValue(targetValue); \n");
//		sb.append("    } \n");
//		sb.append("    var tableIdT = myform.getForm().findField('tableId'); \n");
//		sb.append("    tableIdT.setValue('").append(panel.getTableId()).append("'); \n");
		sb.append("   }); \n");
		sb.append(" }, \n");
		sb.append(" initComponent : function() { \n");
		sb.append("  editWindow=this; \n");
		sb.append("  var tempEditForm = new Ext.FormPanel({ \n");
		sb.append("   frame : true, \n");
		sb.append("   border : true, \n");
		sb.append("   labelAlign : 'right', \n");
		sb.append("   labelWidth : 100, \n");
		sb.append("   url : 'tempSave.action', \n");
		sb.append("   onSubmit : Ext.emptyFn, \n");
		sb.append("   defaultType : 'textfield', \n");
		sb.append("   buttonAlign : 'center', \n");
		sb.append("   bodyStyle : 'padding: 20 25;', \n");
		sb.append("   minButtonWidth : 60, \n");
		sb.append("   items : [").append(form.toString()).append("], \n");
		sb.append("   buttons : [{ \n");
		sb.append("    text : '保存', \n");
		sb.append("    handler : function(btn) { \n");
		sb.append("     if(tempEditForm.getForm().isValid()) { \n");
		sb.append("      tempEditForm.getForm().submit({ \n");
		sb.append("       success : function (tempEditForm,action) { \n");
		sb.append("        Ext.Msg.alert('成功',action.result.msg); \n");
		sb.append("        p").append(panel.getRid()).append(".findById('wyid").append(panel.getId()).append("').getStore().reload(); \n");
		sb.append("        editWindow.hide(); \n");
		sb.append("       }, \n");
		sb.append("       failure : function (tempEditForm,action) { \n");
		sb.append("        Ext.Msg.alert('失败',action.result.msg); \n");
		sb.append("       } \n");
		sb.append("      }); \n");
		sb.append("     } else { \n");
		sb.append("      Ext.Msg.alert('提示','请检查（红线框）输入项是否符合要求！'); \n");
		sb.append("     } \n");
		sb.append("    } \n");
		sb.append("   },{ \n");
		sb.append("    text : '取消', \n");
		sb.append("    handler : function() { \n");
		sb.append("     this.ownerCt.ownerCt.hide(); \n");
		sb.append("    }}] \n");
		sb.append("  }); \n");
		sb.append(" \n");
		sb.append("  Ext.apply(this, { \n");
		sb.append("     frame : true, \n");
		sb.append("     border : true, \n");
		sb.append("     title : '产品信息', \n");
		sb.append("     width : 350, \n");
		sb.append("     height : 250, \n");
		sb.append("     resizable : false, \n");
		sb.append("     modal : true, \n");
		sb.append("     closeAction : 'hide', \n");
		sb.append("     layout : 'fit', \n");
		sb.append("     items : [tempEditForm] \n");
		sb.append("    }); \n");
		sb.append(" \n");
		sb.append("EditW").append(panel.getId()).append(".superclass.initComponent.call(this);");
		sb.append(" } \n");
		sb.append("}); \n");
		
		return sb.toString();
	}
	private boolean comm(ExtPanel panel){
		ds.append("{name:'id',type:'int'}");
		cm.append("{header:'主键',dataIndex:'id',sortable:true,hidden:true}");
		field.append("myform.getForm().findField('temp.id').setValue(result['id']);");
		form.append("{fieldLabel:'面版ID',inputType:'hidden',name:'temp.panelId',value:'").append(panel.getId()).append("'}");
		form.append(",{fieldLabel:'数据表',inputType:'hidden',name:'temp.tableName',value:'").append(panel.getTableName()).append("'}");
		form.append(",{fieldLabel:'主键',inputType:'hidden',name:'temp.id'}");
		form.append(",{fieldLabel:'外键',inputType:'hidden',name:'PID',value:this.tempId}");
		Set<ExtComm> set=panel.getComm();
		for(ExtComm ec:set){
			if("COLNAME".equalsIgnoreCase(ec.getType())) {
				ds.append(",{name:'").append(ec.getColName())
					.append("',type:'").append(PanelUtils.dsType(ec.getColType())).append("'}");
				cm.append(",{header:'").append(ec.getName())
					.append("',dataIndex:'").append(ec.getColName())
					.append("',sortable:true,hidden:")
					.append(PanelUtils.cn2Bool(ec.getHidden())).append("}");
				field.append("myform.getForm().findField('").append(ec.getColName())
					.append("').setValue(result['").append(ec.getColName().toLowerCase()).append("']);");
				form.append(",{fieldLabel:'").append(ec.getName())
					.append("',xtype:'").append(PanelUtils.xtype(ec.getColType()))
					.append("',vtype:'trimblank',width:150,allowBlank :")
					.append(PanelUtils.cn2Bool(ec.getColNullAble())).append(",maxLength:")
					.append(PanelUtils.formLength(ec.getColType()))
					.append(",name:'").append(ec.getColName()).append("'}");
			} else if("CLICK".equalsIgnoreCase(ec.getType())){
				map.put("click", ec.getTargetId());
			} else if("BUTTION".equalsIgnoreCase(ec.getType())){
				if(map.get("butItem")==null) {
					map.put("butItem", "but"+ec.getPanelId()+"_"+ec.getId());
				} else {
					map.put("butItem", map.get("butItem")+",but"+ec.getPanelId()+"_"+ec.getId());
				}
				but.append(makeButtion(ec,panel));
			}
		}
		return true;
	}
	private String makeButtion(ExtComm comm,ExtPanel pan){
		StringBuffer sb=new StringBuffer();
		sb.append("var but").append(comm.getPanelId()).append("_").append(comm.getId());
		sb.append("=new Ext.Button({ \n");
		sb.append(" text:'").append(PanelUtils.butCN(comm.getName())).append("', \n");
		sb.append(" iconCls : 'icon-add', \n");
//		sb.append(" disabled  : true, \n");
		sb.append(" handler:function (){ \n");
		if("add".equalsIgnoreCase(comm.getName())){
			sb.append("   var treeP=p").append(pan.getRid()).append(".findById('wyid").append(comm.getTargetId()).append("'); \n");
			sb.append("   var treeNode = treeP.selModel.selNode; \n");
			sb.append("   if (treeNode == null) { \n");
			sb.append("     Ext.Msg.alert('提示','请选择上级目录！'); \n");
			sb.append("      return; \n");
			sb.append("   } \n");
			sb.append("  var tempEditWin=new EditW").append(comm.getPanelId()).append("({tempId:treeNode.id}); \n");
			sb.append("  tempEditWin.show(); \n");
		} else if("edit".equalsIgnoreCase(comm.getName())){
			sb.append("   var listP=p").append(pan.getRid()).append(".findById('wyid").append(comm.getPanelId()).append("'); \n");
			sb.append("      var selCount = listP.getSelectionModel().getCount(); \n");
			sb.append("      if (selCount != 1) { \n");
			sb.append("       Ext.Msg.alert('提示信息','请选择要修改的数据并只能选择一个数据！'); \n");
			sb.append("       return; \n");
			sb.append("      } \n");
			sb.append("      var records = listP.getSelectionModel().getSelections();");
			sb.append("  var tempEditWin=new EditW").append(comm.getPanelId()).append("({tempId:records[0].get('id')}); \n");
			sb.append("  tempEditWin.initData(); \n");
			sb.append("  tempEditWin.show(); \n");
		} else if("del".equalsIgnoreCase(comm.getName())){
			sb.append("   var listP=p").append(pan.getRid()).append(".findById('wyid").append(comm.getPanelId()).append("'); \n");
			sb.append("      var selCount = listP.getSelectionModel().getCount(); \n");
			sb.append("      if (selCount == 0) { \n");
			sb.append("       Ext.Msg.alert('提示信息','请选择要删除的数据！'); \n");
			sb.append("       return; \n");
			sb.append("      } else { \n");
			sb.append("       var tempIds=''; \n");
			sb.append("       var records = listP.getSelectionModel().getSelections(); \n");
			sb.append("       for (var i = 0; i < selCount; i++) { \n");
			sb.append("        tempIds=tempIds+records[i].get('id')+','; \n");
			sb.append("       } \n");
			sb.append("  Ext.Msg.show({title:'确认删除',msg:'您确认要删除吗？',buttons:Ext.Msg.YESNO,");
			sb.append("    fn : function(bb) {");
			sb.append("    if (bb == 'yes') {");
			sb.append("       Ext.Ajax.request({ \n");
			sb.append("        url : 'tempDel.action', \n");
			sb.append("        params : { \n");
			sb.append("         ids:tempIds, \n");
			sb.append("         tableName:'").append(pan.getTableName()).append("' \n");
			sb.append("        }, \n");
			sb.append("        success : function(response) { \n");
			sb.append("         var result = Ext.decode(response.responseText); \n");
			sb.append("         Ext.Msg.alert('提示',result.msg); \n");
			sb.append("         Ext.getBody().unmask(); \n");
			sb.append("         listP.getStore().reload(); \n");
			sb.append("        }, \n");
			sb.append("        failure : function(response) { \n");
			sb.append("        }, \n");
			sb.append("        scope : this \n");
			sb.append("             }); \n");
			sb.append("     }else {");
			sb.append("	       return;");
			sb.append("	    }");
			sb.append("	   },");
			sb.append("	 	scope : this,");
			sb.append("	 	icon : Ext.MessageBox.QUESTION");
			sb.append("	 });");
			sb.append("      } \n");
		}
		sb.append("  } \n");
		sb.append("}); \n");
		return sb.toString();
	}
	public static void main(String[] args){
		GridPanel gp=new GridPanel();
		ExtPanel p=new ExtPanel();
		System.out.println(gp.make(p));
	}
	StringBuffer cm=new StringBuffer();
	StringBuffer ds=new StringBuffer();
	StringBuffer form=new StringBuffer();
	StringBuffer field=new StringBuffer();
	StringBuffer but=new StringBuffer();
	HashMap<String,Object> map=new HashMap<String,Object>();
}
